package run.jingjing.websocket.autoconfiguration;

import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import run.jingjing.websocket.endpoint.LittlebustersEndpointDemo;
import run.jingjing.websocket.template.WebSocketTemplate;

/**
 * @author: jingjing
 * @date: 2021/6/24
 * @description: littlebusters-weboscket auto configuration
 */
@Slf4j
@Configuration
@ComponentScan(basePackages = {"run.jingjing.websocket","cn.hutool.extra.spring"})
public class LWsAutoConfiguration {

    @Bean
    @ConditionalOnBean({RedisTemplate.class, NacosServiceDiscovery.class})
    public WebSocketTemplate webSocketTemplate(RestTemplate restTemplate, RedisMessageListenerContainer redisMessageListenerContainer, NacosServiceDiscovery nacosServiceDiscovery, RedisTemplate redisTemplate) {
        return new WebSocketTemplate(restTemplate, redisMessageListenerContainer, nacosServiceDiscovery, redisTemplate);
    }

    @Bean
    @ConditionalOnBean({RedisTemplate.class})
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        return container;
    }

    @Bean
    public LittlebustersEndpointDemo littlebustersEndpoint() {
        return new LittlebustersEndpointDemo();
    }

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    @Configuration
    @ConditionalOnMissingBean(RedisTemplate.class)
    public static class RedisTemplateNotFoundConfiguration implements InitializingBean {

        @Override
        public void afterPropertiesSet() {
            log.error("required redisTemplate is not found");
            throw new RuntimeException();
        }
    }

    @Configuration
    @ConditionalOnMissingBean(NacosServiceDiscovery.class)
    public static class NacosServiceDiscoveryNotFoundConfiguration implements InitializingBean {

        @Override
        public void afterPropertiesSet() {
            log.error("required nacosServiceDiscovery is not found");
            throw new RuntimeException();
        }
    }
}
